using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Acme.BookStore.StockManagement.Dtos.ChuRuKuLiuShui;
using Acme.BookStore.StockManagement.Services;
using AutoMapper;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Acme.BookStore.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Text;
using Volo.Abp;
using Microsoft.Extensions.Logging;

namespace Acme.BookStore.StockManagement
{
    /// <summary>
    /// 出入库流水应用服务实现类
    /// </summary>
    public class ChuRuKuLiuShuiAppService : ApplicationService, IChuRuKuLiuShuiAppService
    {
        private readonly IRepository<ChuRuKuLiuShui, int> _chuRuKuLiuShuiRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="chuRuKuLiuShuiRepository">出入库流水仓储</param>
        /// <param name="mapper">对象映射</param>
        public ChuRuKuLiuShuiAppService(
            IRepository<ChuRuKuLiuShui, int> chuRuKuLiuShuiRepository,
            IMapper mapper)
        {
            _chuRuKuLiuShuiRepository = chuRuKuLiuShuiRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取出入库流水分页列表
        /// </summary>
        /// <param name="input">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResultDto<ChuRuKuLiuShuiDto>> GetListAsync(ChuRuKuLiuShuiGetListInputDto input)
        {
            try
            {
                // 构建查询条件
                var queryable = await _chuRuKuLiuShuiRepository.GetQueryableAsync();
                
                // 获取数据库集合
                var query = queryable.AsNoTracking();
                
                // 添加查询条件
                if (!string.IsNullOrEmpty(input.IoOrderCodeOrName))
                {
                    query = query.Where(x => x.IoOrderCode.Contains(input.IoOrderCodeOrName) || 
                                            x.Operator.Contains(input.IoOrderCodeOrName) || 
                                            x.Creator.Contains(input.IoOrderCodeOrName));
                }

                if (!string.IsNullOrEmpty(input.WarehouseName))
                {
                    query = query.Where(x => x.WarehouseName == input.WarehouseName);
                }

                if (!string.IsNullOrEmpty(input.BusinessType))
                {
                    query = query.Where(x => x.BusinessType == input.BusinessType);
                }

                if (!string.IsNullOrEmpty(input.IoType))
                {
                    query = query.Where(x => x.IoType == input.IoType);
                }

                if (input.IoDateStart.HasValue)
                {
                    query = query.Where(x => x.IoDate >= input.IoDateStart.Value);
                }

                if (input.IoDateEnd.HasValue)
                {
                    query = query.Where(x => x.IoDate <= input.IoDateEnd.Value);
                }

                // 获取总数
                var totalCount = await AsyncExecuter.CountAsync(query);

                // 排序
                if (!string.IsNullOrEmpty(input.Sorting))
                {
                    query = query.OrderBy(x => x.Id);
                }
                else
                {
                    query = query.OrderByDescending(x => x.Id);
                }

                // 分页
                query = query.Skip(input.SkipCount).Take(input.MaxResultCount);

                // 获取数据
                var items = await AsyncExecuter.ToListAsync(query);

                // 转换为DTO
                var dtos = _mapper.Map<List<ChuRuKuLiuShui>, List<ChuRuKuLiuShuiDto>>(items);

                // 返回分页结果
                return new PagedResultDto<ChuRuKuLiuShuiDto>(totalCount, dtos);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                Logger.LogError(ex, "查询出入库流水失败");
                throw;
            }
        }

        /// <summary>
        /// 获取出入库流水详情
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns>出入库流水</returns>
        public async Task<ChuRuKuLiuShuiDto> GetAsync(int id)
        {
            try
            {
                // 使用仓储方法获取数据
                var entity = await _chuRuKuLiuShuiRepository.GetAsync(id);
                
                if (entity == null)
                {
                    throw new UserFriendlyException($"未找到ID为{id}的出入库流水记录");
                }

                return _mapper.Map<ChuRuKuLiuShui, ChuRuKuLiuShuiDto>(entity);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "获取出入库流水详情失败");
                throw;
            }
        }

        /// <summary>
        /// 创建出入库流水
        /// </summary>
        /// <param name="input">出入库流水</param>
        /// <returns>创建后的出入库流水</returns>
        public async Task<ChuRuKuLiuShuiDto> CreateAsync(ChuRuKuLiuShuiDto input)
        {
            var entity = _mapper.Map<ChuRuKuLiuShuiDto, ChuRuKuLiuShui>(input);
            entity = await _chuRuKuLiuShuiRepository.InsertAsync(entity);
            return _mapper.Map<ChuRuKuLiuShui, ChuRuKuLiuShuiDto>(entity);
        }

        /// <summary>
        /// 更新出入库流水
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <param name="input">出入库流水</param>
        /// <returns>更新后的出入库流水</returns>
        public async Task<ChuRuKuLiuShuiDto> UpdateAsync(int id, ChuRuKuLiuShuiDto input)
        {
            var entity = await _chuRuKuLiuShuiRepository.GetAsync(id);
            _mapper.Map(input, entity);
            entity = await _chuRuKuLiuShuiRepository.UpdateAsync(entity);
            return _mapper.Map<ChuRuKuLiuShui, ChuRuKuLiuShuiDto>(entity);
        }

        /// <summary>
        /// 删除出入库流水
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public async Task DeleteAsync(int id)
        {
            await _chuRuKuLiuShuiRepository.DeleteAsync(id);
        }
    }
} 